﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using HP.Cachalote.DataModels;
using HP.Cachalote.Repositories.Interfaces;

namespace HP.Cachalote.UnitTests.FakeRepositories
{
    public abstract class FakeRepositoryBase<T> : IRepository<T> where T : DataModelBase
    {
        protected static List<T> DataList;

        public FakeRepositoryBase()
        {
            GenerateInMemoryData();
        }

        public object Add(T entity)
        {
            DataList.Add(entity);
            return entity;
        }

        public T Get(object id)
        {
            return DataList.Where(o => o.ID == (int)id).FirstOrDefault();
        }

        public T Load(object id)
        {
            return Get(id);
        }

        public IQueryable<T> Filter(Expression<Func<T, bool>> expression)
        {
            return DataList.AsQueryable().Where(expression).AsQueryable();
        }

        public IQueryable<T> GetAll()
        {
            return DataList.AsQueryable();
        }

        public int GetRowCount(Expression<Func<T, bool>> expression)
        {
            return DataList.AsQueryable().Where(expression).Count();
        }

        public void Update(T entity)
        {
            T t = DataList.Where(o => o.ID == (int)entity.ID).FirstOrDefault();

            if (t != null)
            {
                int index = DataList.IndexOf(t);
                DataList.RemoveAt(index);
                DataList.Insert(index, entity);
            }
        }

        public void AddOrUpdate(T entity)
        {
            T t = Get(entity.ID);

            if (t == null)
            {
                DataList.Add(entity);
            }
            else
            {
                int index = DataList.IndexOf(t);
                DataList.RemoveAt(index);
                DataList.Insert(index, entity);
            }

        }

        public void Delete(T entity)
        {
            T t = DataList.Where(o => o.ID == (int)entity.ID).FirstOrDefault();

            if (t != null)
            {
                int index = DataList.IndexOf(t);
                DataList.RemoveAt(index);
            }
        }

        protected abstract void GenerateInMemoryData();
    }
}
